package org.crepi22.finecrop;

import java.awt.Rectangle;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;

class MultiCrop extends Thread {
        final private Collection <Rectangle> rect;
        final private float ratio;
        final private int x;
        final private int y;
        final private Continuation continuation;
        final private Photo photo;
        
        MultiCrop(Continuation continuation, Photo photo, Collection<Rectangle> rectangles, int x, int y, float ratio) {
            this.continuation = continuation;
            this .rect = rectangles;
            this.x = x;
            this.y = y;
            this.ratio = ratio;
            this.photo = photo;
        }

        public void run() {
            List<File> results = new ArrayList<File>();
            try {
                for (Rectangle r : rect) {
                    File clippedImageFile = File.createTempFile("clipped", ".jpg"); //$NON-NLS-1$ //$NON-NLS-2$
                    int sx = (int)((r.x - x) / ratio);
                    int sy = (int) ((r.y - y) / ratio);
                    int ex = sx + (int) (r.width / ratio);
                    int ey = sy + (int) (r.height / ratio);
                    String[] command = new String[] {
                            Config.getConvertPath(),
                            "-crop", //$NON-NLS-1$
                            photo.formatBounds(sx,sy,ex,ey),                             
                            photo.getPath(),
                            clippedImageFile.getAbsolutePath()
                    };
                    synchronized (continuation) {
                        continuation.showEffect(true);
                        Process p = Runtime.getRuntime().exec(command);
                        int exit = p.waitFor();
                        if (exit != 0) {
                            throw new IOException(String.format(Messages.getString("MultiCrop.command_error"),exit, Arrays.toString(command))); //$NON-NLS-1$
                        } 
                        results.add(clippedImageFile);

                    }
                }
                continuation.runFiles(results);
            } catch (IOException e) {
                continuation.error(e.getMessage());
            } catch (InterruptedException e) {
                continuation.error(e.getMessage());
            } finally {
                continuation.showEffect(false);
            }
        }

    }
